from base.graph.Graph import Graph
from base.graph.GraphUtil import GraphUtil
from base.graph.Triple import Triple
from base.java.ActionCount import ActionCount
from base.shared.JenaException import JenaException
from base.shared.impl.PrefixMappingImpl import PrefixMappingImpl
from base.graph import Triple as TripleOut


class GraphMem2(Graph):

    def __init__(self, tripleStore):
        self.tripleStore = tripleStore
        self.pm = None
        self.closed = False

    def dependsOn(self, other):
        return self == other

    def getPrefixMapping(self):
        if self.pm is None:
            self.pm = PrefixMappingImpl()
        return self.pm

    def add(self, t):
        self.checkOpen()
        self.tripleStore.add(t)

    def addSPO(self, s, p, o):
        self.add(Triple.create(s, p, o))

    def delete(self, t):
        self.checkOpen()
        self.tripleStore.remove(t)

    def deleteSPO(self, s, p, o):
        self.delete(Triple.create(s, p, o))

    def find(self, m):
        self.checkOpen()
        return self.tripleStore.find(m)

    def findSPO(self, s, p, o):
        return self.find(Triple.create(s, p, o))

    def findAll(self):
        pass

    def isIsomorphicWith(self, g):
        pass

    def containsSPO(self, s, p, o):
        return self.contains(Triple.create(s, p, o))

    def contains(self, t):
        it = self.find(t)
        try:
            return it.hasNext()
        except JenaException:
            return False

    def clear(self):
        self.tripleStore.clear()

    def remove(self, s, p, o):
        GraphUtil.remove(self, s, p, o)

    def close(self):
        self.tripleStore.clear()
        self.closed = True

    def isEmpty(self):
        return not self.contains(TripleOut.ANY)

    def size(self):
        it = self.find(TripleOut.ANY)
        ac = ActionCount()
        it.forEach(ac)
        return ac.count

    def isClosed(self):
        return self.closed

    def checkOpen(self):
        if self.isClosed():
            raise JenaException('this graph is closed')


emptyGraph = GraphMem2(None)
